const jwt = require('koa-jwt')
const _ = require('lodash')
const {User} = require('../models')
const {md5} = require('../lib/utils')

module.exports = function (router) {
  router.post('/auth', function * () {
    this.checkBody('username').notEmpty('请输入账号。')
    this.checkBody('password').notEmpty('请输入密码。')
    if (this.errors) this.throwError(401)

    let {username, password} = this.request.body
    let user = User.findOne({username}).exec()
    if (!user) this.throw('用户名不存在。', 401)
    if (user.password !== md5(password)) this.throw('密码错误', 401)

    let token = jwt.sign(_.pick(user, ['_id', 'username']))

    this.body = this.apiSuccess({token})
  })
}
